﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpHelpers.Sockets
{
    public class SocketBufferHelper
    {
        /// <summary>
        /// 发送信息编码
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="msgBt"></param>
        public static void EncodeMessage(byte[] bt, byte[] msgBt, byte[] m_header, int headerSize)
        {
            //mask
            bt[0] = m_header[0];
            bt[1] = m_header[1];
            bt[2] = m_header[2];
            bt[3] = m_header[3];

            //4~7: 整條消息長度
            byte[] bt2 = BitConverter.GetBytes(msgBt.Length);
            for (int i = 0; i < bt2.Length; i++)
            {
                bt[4 + i] = bt2[i];
            }

            //信息内容
            for (int i = 0; i < msgBt.Length; i++)
            {
                bt[i + headerSize] = msgBt[i];
            }
        }

        public static int GetMessageMark(byte[] value, int Offset)
        {
            byte[] bt = new byte[4];

            for (int i = 0; i < bt.Length; i++)
            {
                bt[i] = value[i + Offset];
            }

            int iValue = BitConverter.ToInt32(bt, 0);

            return iValue;
        }

        public static int GetMessageSize(byte[] value, int Offset)
        {
            byte[] bt = new byte[4];

            bt[0] = value[4 + Offset];
            bt[1] = value[5 + Offset];
            bt[2] = value[6 + Offset];
            bt[3] = value[7 + Offset];

            int iValue = BitConverter.ToInt32(bt, 0);

            return iValue;
        }

        public static void CopyToMsgBuffer(byte[] destBuffer, byte[] sourceBuffer, int destOffset, int sourceOffset, int len)
        {
            for (int i = 0; i < len; i++)
            {
                if ((destOffset + i) < destBuffer.Length && (sourceOffset + i) < sourceBuffer.Length)
                {
                    destBuffer[destOffset + i] = sourceBuffer[sourceOffset + i];
                }
            }
        }

        /// <summary>
        /// 二进制转为16进制字符串
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static string ByteBinaryToHexString(byte[] bt)
        {
            string reValue = string.Empty;

            for (int i = 0; i < bt.Length; i++)
            {
                string tempValue = string.Format("{0:x}", Convert.ToString(bt[i], 16));

                if (tempValue.Length == 1)
                {
                    tempValue = "0" + tempValue;
                }

                reValue += tempValue + ",";
            }

            if (reValue.Length > 0)
            {
                reValue = reValue.Substring(0, reValue.Length - 1);
            }

            return reValue;
        }
    }
}
